/**
 * @filename SystemAction.java
 * @package com.tianjian.action.system[MySSM]
 * @description 系统第一个Action
 * @author 胡正衛
 * @date 2012-6-3 下午12:13:17
 * @version v0.1
 */
package com.tianjian.oa.system;

import java.util.List;

import javax.servlet.http.Cookie;

import org.springframework.beans.factory.annotation.Autowired;

import com.tianjian.common.BaseAction;
import com.tianjian.common.Config;
import com.tianjian.common.Criteria;
import com.tianjian.common.online.OnLineUsers;
import com.tianjian.oa.system.pojos.UserInfo;
import com.tianjian.oa.system.services.RoleService;
import com.tianjian.oa.system.services.UserService;
import com.tianjian.util.GeneralUitl;

/**
 * @author 胡正衛
 */
public class SystemAction extends BaseAction {

	private static final long serialVersionUID = 8596912747784698508L;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	/** 登陆按钮按下 */
	private String submit;

	/** 登陆用户名 */
	private String username;

	/** 登陆密码 */
	private String password;

	/** 登陆反馈提示信息 */
	private String message;

	/** 验证码 */
	private String kaptcha;

	/** 自动登陆 */
	private String autologin;

	public SystemAction() {
		super("系统登陆");
	}

	public String login() {
		if (userinfo != null) {
			return SUCCESS;
		}
		if (submit == null) { // 不是点击登陆按钮,则跳到登陆界面
			getCookie(); // 获取客户端cookies判断是否自动登陆
			if (autologin == null) { // 如果是不是自动登陆, 则跳到登陆界面
				return LOGIN;
			}
		}
		if (username == null || username.length() == 0 || password == null || password.length() == 0) {
			clearCookie(); // 登陆失败,清除客户端cookie中的登陆信息
			message = "请输入用户名和密码";
			return LOGIN;
		}
		if (autologin != null) {
			execLogin();
		} else {
			String kaptcha = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			this.kaptcha = kaptcha;
			if (kaptcha == null || this.kaptcha != null && this.kaptcha.equals(kaptcha)) {
				execLogin();
			} else {
				message = "验证码不正确";
			}
		}
		if (message == null) { // 登陆成功
			if (autologin != null) {
				setCookie(); // 登陆成功,设置登陆信息到客户端cookies中
			}
			userinfo.setSessionId(session.getId());
			userinfo.setLogintime(new java.util.Date());
			userinfo.setLoginip(GeneralUitl.GetRealIP(request));
			session.setAttribute(Config.SESSION_USERINFO, userinfo);
			session.setAttribute(Config.SESSION_LISTENER, new OnLineUsers(userinfo));
			logging.login(userinfo);
			return SUCCESS;
		} else {
			clearCookie(); // 登陆失败,清除客户端cookie中的登陆信息
			return LOGIN;
		}
	}

	/**
	 * 当前台发送关闭窗口或刷新窗口事件时, 更新session有效期为10秒
	 * 10秒后触发session销毁事件
	 */
	public void close() {
		session.setMaxInactiveInterval(5);
	}

	public String logout() {
		session.removeAttribute(Config.SESSION_USERINFO);
		session.invalidate();
		clearCookie(); // 登陆失败,清除客户端cookie中的登陆信息
		return SUCCESS;
	}

	public String index() {
		return SUCCESS;
	}

	/**
	 * 执行登陆事件
	 * @return
	 */
	private void execLogin() {
		try {
			Criteria criteria = new Criteria();
			criteria.put("username", username);
			criteria.put("password", password);
			List<UserInfo> users = userService.getData(criteria);
			if (users != null && users.size() > 0) {
				UserInfo user = users.get(0);
				if (new Integer(0).equals(user.getState())) {
					message = "账户已被停用.";
				} else if (user.getExpired() != null && (System.currentTimeMillis() - user.getExpired().getTime()) < 0) {
					message = "账户已过期.";
				} else {
					user.setRoles(roleService.getRole(user.getId(), false));
					if (user.getRoles() == null || user.getRoles().size() == 0) {
						message = "没有权限的账户.";
					} else {
						userinfo = user;
					}
				}
			} else {
				message = "用户名或密码错误.";
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "登陆时发生错误,请联系系统管理员.";
		}
	}

	/* (non-Javadoc)
	 * @see com.tianjian.system.BaseAction#get()
	 */
	@Override
	public String get() { return null; }

	/* (non-Javadoc)
	 * @see com.tianjian.system.BaseAction#view()
	 */
	@Override
	public String view() {
		return SUCCESS;
	}

	/* (non-Javadoc)
	 * @see com.tianjian.system.BaseAction#add()
	 */
	@Override
	public String add() { return null; }

	/* (non-Javadoc)
	 * @see com.tianjian.system.BaseAction#edit()
	 */
	@Override
	public String edit() { return null; }

	/* (non-Javadoc)
	 * @see com.tianjian.system.BaseAction#del()
	 */
	@Override
	public String del() { return null; }

	public String js() {
		return SUCCESS;
	}

	/***
	 * 设置cookies到客户端
	 */
	private void setCookie() {
		Cookie cookie = new Cookie("autologin", autologin);
		cookie.setMaxAge(604800);
		response.addCookie(cookie);
		cookie = new Cookie("username", username);
		cookie.setMaxAge(604800);
		response.addCookie(cookie);
		cookie = new Cookie("password", password);
		cookie.setMaxAge(604800);
		response.addCookie(cookie);
	}

	/**
	 * 获取客户端的cookies
	 */
	private void getCookie() {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie c = cookies[i];
				if ("autologin".equals(c.getName())) {
					if (c.getValue() != null) {
						autologin = c.getValue();
					}
				} else if ("username".equals(c.getName())) {
					username = c.getValue();
				} else if ("password".equals(c.getName())) {
					password = c.getValue();
				}
			}
		}
	}

	/**
	 * 清除cookies中登陆信息
	 */
	private void clearCookie() {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie c = cookies[i];
				if ("autologin".equals(c.getName())) {
					c.setValue(null);
					c.setMaxAge(0);
					response.addCookie(c);
				} else if ("password".equals(c.getName())) {
					c.setValue(null);
					c.setMaxAge(0);
					response.addCookie(c);
				}
			}
		}
	}

	/**
	 * 设置[登陆按钮按下]
	 * @param submit
	 */
	public void setSubmit(String submit) {
		this.submit = submit;
	}

	/**
	 * 获取[登陆反馈提示信息]
	 * @return 登陆反馈提示信息
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * 设置[登陆用户名]
	 * @param username
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * 设置[登陆密码]
	 * @param password
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * 设置[验证码]
	 * @param kaptcha
	 */
	public void setKaptcha(String kaptcha) {
		this.kaptcha = kaptcha;
	}

	/**
	 * 设置[自动登陆]
	 * @param autologin
	 */
	public void setAutologin(String autologin) {
		this.autologin = autologin;
	}

}
